package com.sqx.modules.health.controller;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sqx.modules.goods.dao.GoodsShopDao;
import com.sqx.modules.goods.service.GoodsService;
import com.sqx.modules.health.common.Constants;
import com.sqx.modules.health.common.Result;
import com.sqx.modules.health.entity.Hospital;
import com.sqx.modules.health.entity.ServicetypeByHealth;
import com.sqx.modules.health.service.IHospitalService;
import com.sqx.modules.health.service.IServicetypeService;
import com.sqx.modules.health.utils.ExcelImportUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 医院信息 前端控制器
 * </p>
 *
 * @author gxy
 * @since 2022-04-14
 */

@Api(value = "医院信息", tags = "", description = "")
@RestController
@RequestMapping("/health/hospital")
public class HospitalController {
    @Autowired
    private IHospitalService hospitalService;

    @Autowired
    private IServicetypeService typeService;

    @Autowired
    private GoodsService goodsService;

    @Autowired
    private GoodsShopDao goodsShopDao;

    // 新增或更新
    @PostMapping("/save")
    @ApiOperation(value = "新增或更新医院信息", notes = "新增或更新医院信息")
    @Transactional
    public Result save(@RequestBody Hospital hospital) {
        if (ObjectUtil.isEmpty(hospital.getId())) {
            try {
                // 执行新增操作并获取到最新的id
                Long aLong = hospitalService.resultIdSave(hospital);
                QueryWrapper<ServicetypeByHealth> wrapper = new QueryWrapper<>();
                wrapper.eq("hid", 1);
                List<ServicetypeByHealth> serviceTypeList = typeService.list(wrapper);
                serviceTypeList.forEach(item ->{
                    item.setId(null);
                    item.setHid(aLong);
                    typeService.save(item);
                });
                return Result.success("success");
            } catch (Exception e) {
                e.printStackTrace();
                return Result.error(Constants.CODE_500, "error");
            }
        } else {
            return Result.success(hospitalService.saveOrUpdate(hospital));
        }

    }

    // 根据ID删除
    @GetMapping("/del/{id}")
    @ApiOperation(value = "根据ID删除医院信息", notes = "根据ID删除医院信息")
    public Result delete(@PathVariable Integer id) {
        return Result.success(hospitalService.removeById(id));
    }

    @GetMapping("/shopList")
    @ApiOperation(value = "根据ID删除医院信息", notes = "根据ID删除医院信息")
    public Result shopList() {
        return Result.success(goodsShopDao.selectList(null));
    }

    // 根据IDS删除
    @PostMapping("/del/batch")
    @ApiOperation(value = "根据IDS删除医院信息", notes = "根据IDS删除医院信息")
    public Result deleteBatch(@RequestParam List<Integer> ids) {
        return Result.success(hospitalService.removeByIds(ids));
    }

    // 查询全部
    @GetMapping("/findAll")
    @ApiOperation(value = "查询全部医院信息", notes = "查询全部医院信息")
    public Result findAll() {
        return Result.success(hospitalService.list());
    }

    // 根据ID查询一条记录
    @GetMapping("/findOne")
    @ApiOperation(value = "根据ID查询一条记录医院信息", notes = "根据ID查询一条记录医院信息")
    public Result findOne(@RequestParam Integer id) {
        return Result.success(hospitalService.getById(id));
    }

    // 分页查询
    @GetMapping("/findPage")
    @ApiOperation(value = "分页查询医院信息", notes = "分页查询医院信息")
    public Result findPage(@RequestParam Integer pageNum,
                           @RequestParam Integer pageSize,
                           @RequestParam(required = false, defaultValue = "") String searchName,
                           @RequestParam(required = false, defaultValue = "") Long hid) {
        QueryWrapper<Hospital> queryWrapper = new QueryWrapper<Hospital>()
                .like(StringUtils.isNotBlank(searchName), "name", searchName)
                .orderByAsc("id").eq(ObjectUtil.isNotEmpty(hid), "id", hid).or().eq(ObjectUtil.isNotEmpty(hid), "pid", hid);
        List<Hospital> list = hospitalService.list(queryWrapper);
        List<Long> idList = new ArrayList<>();
        for (Hospital hospital : list) {
            if (ObjectUtil.isNotEmpty(hospital.getPid())){
                idList.add(hospital.getId());
            }
        }
        if (ObjectUtil.isNotEmpty(idList)) {
            QueryWrapper<Hospital> wrapper = new QueryWrapper<Hospital>().in("pid", idList);
            List<Hospital> hospitals = hospitalService.list(wrapper);
            if (ObjectUtil.isNotEmpty(hospitals)) {
                list.addAll(hospitals);
            }
        }
        for (Hospital record : list) {
            if (ObjectUtil.isNotEmpty(record.getPid())) {
                //处理pid上级医院的层级关系
                    Hospital byId = hospitalService.getById(record.getPid());
                    record.setPName(byId.getName());
            }
        }
        Page<Hospital> result = new Page<>();
        result.setRecords(list);
        result.setTotal(list.size());
        return Result.success(result);
    }

    @PostMapping("/insertBath")
    public Result insertBath(MultipartFile file) {

        Hospital hospital = new Hospital();

        List<List<String>> list = ExcelImportUtil.importExcel(file);
        if (ObjectUtil.isEmpty(list)) {
            return Result.error(Constants.CODE_500, "导入失败,请检查文件!!!");
        }
        int succ = 0;
        int err = 0;
        // 设置值  并将值添加到数据库中
        try {
            for (List<String> param : list) {
                hospital.setId(null);
                hospital.setName(param.get(0));
                hospital.setAbbreviation(param.get(1));
                hospital.setContacts(param.get(2));
                hospital.setPhone(param.get(3));
                hospital.setAddress(param.get(4));
                if (filterHospital(hospital.getName())) {
                    err += 1;
                    continue;
                }
                hospitalService.save(hospital);
                succ += 1;
            }
            return Result.success("成功导入" + succ + "条,重复数据" + err + "条");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(Constants.CODE_500, "导入失败!!!");
        }
    }

    /**
     * 判断当前医院是否已经存在
     *
     * @param name
     * @return
     */
    private boolean filterHospital(String name) {
        int num = hospitalService.filterHospital(name);
        if (num != 0) {
            return true;
        } else {
            return false;
        }
    }
    // 查询全部
    @GetMapping("/findHospitalSelects")
    @ApiOperation(value = "查询全部医院信息", notes = "查询全部医院信息")
    public Result findHospitalSelects( @RequestParam(required = false, defaultValue = "") Long hid) {
        QueryWrapper<Hospital> queryWrapper = new QueryWrapper<Hospital>()
                .like(ObjectUtil.isNotEmpty(hid), "hid", hid)
                .eq("isdelete",0)
                .orderByAsc("id").eq(ObjectUtil.isNotEmpty(hid), "id", hid).or().eq(ObjectUtil.isNotEmpty(hid), "pid", hid);
        List<Hospital> list = hospitalService.list(queryWrapper);
        return Result.success(hospitalService.list());
    }


}

